package commmon.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.FileSystemNotFoundException;

/**
 * @author 22246
 */
public class CheckSessionFilter implements Filter {
    private HttpServletRequest req;
    private HttpServletResponse resp;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        req = (HttpServletRequest) servletRequest;
        String requestURI1 = req.getRequestURI();
        resp = (HttpServletResponse) servletResponse;
        String url = req.getContextPath();
        Object obj = req.getSession().getAttribute("userInfo");
        String requestURI = req.getRequestURI();
        String filterUrl = requestURI.substring(requestURI.lastIndexOf("/") + 1, requestURI.length());

        System.out.print(filterUrl+"====================="+filterUrl.matches(".*\\.(jpg|png|html|php)$"));
        if (requestURI.equals("/") || filterUrl.equals("staffLogin") || filterUrl.equals("login.jsp") || filterUrl.equals("register.jsp") || filterUrl.endsWith("jpg") || filterUrl.endsWith("png") || filterUrl.endsWith("html") || filterUrl.endsWith("php") || filterUrl.endsWith("json")) {
            filterChain.doFilter(servletRequest, servletResponse);
        }else{
            System.out.println(filterUrl);
            if(obj==null){
                req.getSession().setAttribute("loginErro","非法入侵，请登录");
                resp.sendRedirect(url+"/");
            }else{
                req.getSession().setAttribute("loginErro","");
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy() {

    }

}
